#!/bin/sh
# author ruoyi
# ./deploy.sh start 启动
# ./deploy.sh stop 停止
# ./deploy.sh restart 重启
# ./deploy.sh status 状态
AppName=ruoyi-admin.jar
AppPort=8080
JAVA_HOME=/usr/local/java/jdk1.8.0_271/bin

# JVM参数
JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512M -Xmx512M -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512M -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC"
APP_HOME=$(pwd)
LOG_PATH=$APP_HOME/logs/$AppName.log

if [ "$1" = "" ]; then
  echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
  exit 1
fi

function start() {
  PID=$(ps -ef | grep java | grep $AppName | grep -v grep | awk '{print $2}')

  if [ x"$PID" != x"" ]; then
    echo "$AppName 正在运行..."
  else
    nohup ${JAVA_HOME}/java -jar $JVM_OPTS $AppName >/dev/null 2>&1 &

    PID=$(lsof -i:$AppPort | grep "LISTEN" | awk '{print $2}')
    until [ -n "$PID" ]; do
      PID=$(lsof -i:$AppPort | grep "LISTEN" | awk '{print $2}')
    done
    echo "$AppName 启动完成..."
  fi
}

function stop() {
  PID=""
  query() {
    PID=$(ps -ef | grep java | grep $AppName | grep -v grep | awk '{print $2}')
  }

  query
  if [ x"$PID" != x"" ]; then
    kill -9 $PID
    echo "$AppName 已停止成功."
  else
    echo "$AppName 未运行"
  fi
}

function restart() {
  stop
  sleep 2
  start
}

function status() {
  PID=$(ps -ef | grep java | grep $AppName | grep -v grep | wc -l)
  if [ $PID != 0 ]; then
    echo "$AppName 正在运行..."
  else
    echo "$AppName 未运行..."
  fi
}

case $1 in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  restart
  ;;
status)
  status
  ;;
*) ;;
esac
